<template>
    <div class="qrcode-container">
        <div class="control-panel">
            <n-tabs type="line" @update:value="handleTabChange">
                <n-tab-pane name="generate" tab="生成二维码">
                    <div class="input-group">
                        <n-input
                            v-model:value="text"
                            type="textarea"
                            placeholder="请输入要生成二维码的文本"
                            :autosize="{ minRows: 3, maxRows: 5 }"
                        />
                        <div class="options">
                            <n-select
                                v-model:value="size"
                                :options="sizeOptions"
                                placeholder="选择大小"
                                class="size-select"
                            />
                            <n-button type="primary" @click="generateQRCode" :disabled="!text">
                                生成二维码
                            </n-button>
                            <n-button @click="downloadQRCode" :disabled="!qrcodeUrl">
                                下载
                            </n-button>
                        </div>
                    </div>
                </n-tab-pane>
                
                <n-tab-pane name="scan" tab="识别二维码">
                    <div class="scan-container">
                        <n-upload
                            accept="image/*"
                            :show-file-list="false"
                            @change="handleFileSelect"
                        >
                            <n-button>选择图片</n-button>
                        </n-upload>
                        <div v-if="scanResult" class="scan-result">
                            <div class="result-label">识别结果：</div>
                            <n-input
                                type="textarea"
                                v-model:value="scanResult"
                                readonly
                                :autosize="{ minRows: 2, maxRows: 5 }"
                            />
                            <n-button size="small" @click="copyResult">
                                复制结果
                            </n-button>
                        </div>
                    </div>
                </n-tab-pane>
            </n-tabs>
        </div>

        <div class="result-panel">
            <div v-if="!qrcodeUrl && !previewImage" class="empty-tip">
                生成或识别二维码
            </div>
            <div v-else-if="qrcodeUrl" class="qrcode-display">
                <img :src="qrcodeUrl" :width="size" :height="size" alt="QR Code" />
            </div>
            <div v-else-if="previewImage" class="preview-display">
                <img :src="previewImage" alt="Preview" style="max-width: 100%; max-height: 100%;" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import QRCode from 'qrcode'
import jsQR from 'jsqr'
import view from '@renderer/util/ui/ViewUtil'

// 输入文本
const text = ref('')
// 二维码URL
const qrcodeUrl = ref('')
// 预览图片
const previewImage = ref('')
// 二维码大小
const size = ref(256)
// 扫描结果
const scanResult = ref('')

// 大小选项
const sizeOptions = [
    { label: '128x128', value: 128 },
    { label: '256x256', value: 256 },
    { label: '512x512', value: 512 },
    { label: '1024x1024', value: 1024 }
]

// 生成二维码
const generateQRCode = async () => {
    if (!text.value) {
        view.alertErrorMessage('请输入文本')
        return
    }

    try {
        const url = await QRCode.toDataURL(text.value, {
            width: size.value,
            margin: 1,
            color: {
                dark: '#000000',
                light: '#ffffff'
            }
        })
        qrcodeUrl.value = url
        previewImage.value = ''
        scanResult.value = ''
    } catch (error) {
        view.alertErrorMessage('生成二维码失败')
        console.error('生成二维码失败:', error)
    }
}

// 下载二维码
const downloadQRCode = () => {
    if (!qrcodeUrl.value) return

    const link = document.createElement('a')
    link.download = `qrcode-${Date.now()}.png`
    link.href = qrcodeUrl.value
    link.click()
}

// 处理文件选择
const handleFileSelect = async (data: { file: { file: File } }) => {
    const file = data.file.file
    if (!file) return

    try {
        // 使用 FileReader 读取图片
        const reader = new FileReader()
        reader.onload = async (e) => {
            try {
                const img = new Image()
                img.src = e.target?.result as string
                
                await new Promise((resolve, reject) => {
                    img.onload = resolve
                    img.onerror = reject
                })

                // 创建 canvas 并绘制图片
                const canvas = document.createElement('canvas')
                canvas.width = img.width
                canvas.height = img.height
                const ctx = canvas.getContext('2d')
                if (!ctx) throw new Error('Failed to get canvas context')
                
                ctx.drawImage(img, 0, 0)
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
                
                // 使用 jsQR 解析二维码
                const code = jsQR(imageData.data, imageData.width, imageData.height)
                
                if (code) {
                    scanResult.value = code.data
                    // 使用 canvas 的 toDataURL 作为预览图片
                    previewImage.value = canvas.toDataURL('image/png')
                } else {
                    view.alertErrorMessage('未能识别出二维码')
                    scanResult.value = ''
                    previewImage.value = ''
                }
            } catch (error) {
                console.error('识别二维码失败:', error)
                view.alertErrorMessage('识别二维码失败')
                scanResult.value = ''
                previewImage.value = ''
            }
        }

        reader.readAsDataURL(file)
        qrcodeUrl.value = ''
    } catch (error) {
        console.error('读取文件失败:', error)
        view.alertErrorMessage('读取文件失败')
        scanResult.value = ''
        previewImage.value = ''
    }
}

// 复制识别结果
const copyResult = () => {
    if (!scanResult.value) return
    
    navigator.clipboard.writeText(scanResult.value)
        .then(() => {
            view.alertSuccessMessage('复制成功')
        })
        .catch(() => {
            view.alertErrorMessage('复制失败')
        })
}

// 添加处理 tab 切换的方法
const handleTabChange = (tabName: string) => {
    // 清空图片显示和相关状态
    qrcodeUrl.value = ''
    previewImage.value = ''
    scanResult.value = ''
    
    if (tabName === 'generate') {
        // 切换到生成页面时清空文本
        text.value = ''
    }
}
</script>

<style scoped>
.qrcode-container {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.control-panel {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.input-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.options {
    display: flex;
    gap: 8px;
    align-items: center;
}

.size-select {
    width: 120px;
}

.result-panel {
    flex: 1;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: white;
}

.empty-tip {
    color: var(--text-color-3);
}

.qrcode-display, .preview-display {
    padding: 16px;
    background-color: white;
}

.qrcode-display img, .preview-display img {
    display: block;
}

.scan-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 16px 0;
}

.scan-result {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.result-label {
    font-weight: 500;
}
</style>